/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socketsudp;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author epulapp
 */
public class Communication extends Thread {

    DatagramSocket s;
    DatagramPacket dpRecus;

    public Communication(DatagramPacket p) throws UnsupportedEncodingException, SocketException {
        this.dpRecus = p;
        this.s = new DatagramSocket();
    }

    @Override
    public void run() {
        try {
            // Envoi reponse
                String str = new String(this.dpRecus.getData(), "ASCII").trim();
                byte[] bRep = str.getBytes();
                DatagramPacket r = new DatagramPacket(bRep, bRep.length, this.dpRecus.getAddress(), this.dpRecus.getPort());
                s.send(r);
            while (!str.equals("END")) {
                // Reception message
                byte[] data = new byte[8186];
                dpRecus = new DatagramPacket(data, data.length);
                s.receive(dpRecus);
                str = new String(dpRecus.getData(), "ASCII").trim();
                System.out.println("Message reçus sur thread " + this.getId() + " : " + str);
                // Envoi reponse
                str = new String(this.dpRecus.getData(), "ASCII").trim();
                bRep = str.getBytes();
                r = new DatagramPacket(bRep, bRep.length, this.dpRecus.getAddress(), this.dpRecus.getPort());
                s.send(r);
            }
            System.out.println("Thread " + this.getId() + " temine.");
        } catch (SocketException ex) {
            Logger.getLogger(Communication.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Communication.class.getName()).log(Level.SEVERE, null, ex);
        }
    } // run()
}
